/**
 * Copyright 2014 opencxa.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cxa.rpc.transportChannel.json.webSocket;

import java.net.URI;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;


/**
 * @author Christopher Armenio
 */
public class ClientWebSocketJsonTransportChannel extends WebSocketJsonTransportChannel
{
	private WebSocketClient client = null;
	
	
	public boolean connect(String destUriIn)
	{
		// don't try to connect if we are already connected
		if( this.isConnected() ) return false;
		
		boolean retVal = false;
		try
		{
			if( this.client == null ) this.client = new WebSocketClient();
			URI destUri = new URI(destUriIn);
			
			this.client.start();
			Future<Session> fut = this.client.connect(this, destUri, new ClientUpgradeRequest());
			this.session = fut.get(10, TimeUnit.SECONDS);
			this.logger.debug("owns connection to " + this.session.getRemoteAddress().toString());
			this.notifyListeners_onConnect();
			retVal = true;
		}
		catch( Exception e )
		{
			this.logger.error(String.format("could not connect to remote: '%s", e.getMessage()));
			this.session = null;
		}
		
		return retVal;
	}
	
	
	@Override
    public void onWebSocketClose(int statusCodeIn, String reasonStringIn)
	{
		try
		{
			// TODO is this needed? it seems to created InterruptedExceptions
			// this.client.stop();
		} catch (Exception e) { this.client = null; }
		super.onWebSocketClose(statusCodeIn, reasonStringIn);
	}
}
